﻿// Copyright (c) 2014 Bryan C. O'Connell
// http://wsubi.codeplex.com/license
// Purpose: This class detects, stores and provides information about the scripts - where and what they are.

using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using Wsubi.Code.Utilities;

namespace Wsubi.Code
{
    public class ScriptData
    {
        private string _ScriptsFolder;
        private string[] _ListOfScripts;
        private Dictionary<string, string> _ScriptFileBin;

        public void BuildDataStores(string ScriptsFolder)
        {
            Guard.ConfirmFolderExists(ScriptsFolder);
            _ScriptsFolder = ScriptsFolder;

            BuildScriptList();
            BuildScriptFileBin();
        }

        public string ShareScriptsFolder()
        {
            return _ScriptsFolder;
        }

        public string[] ShareListOfScripts()
        {
            return _ListOfScripts;
        }

        public Dictionary<string, string> ShareScriptFileBin()
        {
            return _ScriptFileBin;
        }

        private void BuildScriptList() 
        {
            _ListOfScripts = new DirectoryInfo(_ScriptsFolder).GetFiles().Select(file => file.Name).ToArray();
            Guard.MinimumNumberOfArrayElements(_ListOfScripts, 1);
        }

        /// <remarks>IMPORTANT!: File name (key) is stored in ToLower state to standardize casing.
        /// This may need to be accounted for whenever a lookup is performed.</remarks>
        private void BuildScriptFileBin() 
        {
            _ScriptFileBin = new Dictionary<string, string>();

            foreach (string File in _ListOfScripts)
            {
                string FileContents = GetScriptFileContents(File);                
                _ScriptFileBin.Add(File.ToLower(), FileContents);
            }
        }

        private string GetScriptFileContents(string FileToRead)
        {
            string FileContents = "";
            string FilePath = _ScriptsFolder + "\\" + FileToRead;

            Guard.ConfirmFileExists(FilePath);
            using (StreamReader Reader = new StreamReader(FilePath))
            {
                FileContents = Reader.ReadToEnd();
            }

            return FileContents;
        }
    }
}
